<?php

namespace App\Crontab;

use App\Model\ActivityModel;
use App\Model\VestSignQueueModel;
use EasySwoole\Component\WaitGroup;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;
use EasySwoole\EasySwoole\Logger;
use EasySwoole\ORM\DbManager;
use EasySwoole\ORM\Exception\Exception;
use EasySwoole\Pool\Exception\PoolEmpty;
use EasySwoole\Pool\Manager;
use Throwable;

class AddVirtualSignQueue extends AbstractCronTask
{
    public static function getRule(): string
    {
        // TODO: Implement getRule() method.
        return '0 0 * * *';
    }

    public static function getTaskName(): string
    {
        // TODO: Implement getTaskName() method.
        //定时任务名称
        return '虚拟用户模拟打卡插入队列';
    }

    function run(int $taskId, int $workerIndex)
    {
        // TODO: Implement run() method.
        // 定时任务处理逻辑
        Logger::getInstance()->info('虚拟用户模拟打卡插入队列 开始时间:' . date('Y-m-d H:i:s'));
        try {
            $list = DbManager::getInstance()->invoke(function ($client) {
                return ActivityModel::invoke($client)
                    ->where('status', 1)
                    ->where('start_date', date('Y-m-d'), '<=')
                    ->where('end_date', date('Y-m-d'), '>=')
                    ->order('id', 'asc')
                    ->all();
            });
        } catch (Exception $e) {
            $list = false;
        } catch (PoolEmpty $e) {
            $list = false;
        } catch (Throwable $e) {
            $list = false;
        }

        if (!$list) {
            Logger::getInstance()->info('虚拟用户模拟打卡插入队列---没有参与用户 结束时间:' . date('Y-m-d H:i:s'));
            return false;
        }

        $wait = new WaitGroup();
        foreach ($list as $v) {
            $wait->add();
            go(function () use ($wait, $v) {
                mt_srand();
                $redis = Manager::getInstance()->get('redis')->getObj();

                $userIds = $redis->zRange('set_join_fictitious_' . $v->id, '+inf', '-inf');

                Manager::getInstance()->get('redis')->recycleObj($redis);

                if (count($userIds) > 0) {
                    $bulkInsertData = [];
                    foreach ($userIds as $k => $virtualApplyUserId) {
                        if ($v->game_type == 1) {
                            $jobTime = mt_rand(strtotime(date('Y-m-d ' . $v->start_time)), strtotime(date('Y-m-d ' . $v->end_time)) - 600);
                        } elseif ($v->game_type == 2) {
                            $jobTime = mt_rand(strtotime(date('Y-m-d ' . $v->start_time)), strtotime(date('Y-m-d ' . $v->start_time)) + 2);
                        } else {
                            $jobTime = mt_rand(strtotime(date('Y-m-d ' . $v->start_time)), strtotime(date('Y-m-d ' . $v->start_time)) + 2);
                        }
                        $bulkInsertData[$k] = [
                            'user_id' => $virtualApplyUserId,
                            'activity_id' => $v->id,
                            'is_done' => 2,
                            'job_time' => $jobTime,
                            'create_time' => time(),
                            'update_time' => time(),
                        ];
                    }

                    VestSignQueueModel::create()->saveAll($bulkInsertData);
                }

                $wait->done();
            });
        }
        $wait->wait();
        Logger::getInstance()->info('虚拟用户模拟打卡插入队列 结束时间:' . date('Y-m-d H:i:s'));
        return true;
    }

    function onException(Throwable $throwable, int $taskId, int $workerIndex)
    {
        // TODO: Implement onException() method.
        echo $throwable->getMessage();
    }
}